package com.dgz.test.controller;

import com.alibaba.cloud.ai.dashscope.audio.synthesis.*;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.ByteBuffer;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: DongGuoZhen
 * @Date: 2025/07/22/14:37
 * @Description:
 */
// 对话模型 文本生语音
@RestController
@RequestMapping("/audio")
public class AudioModelController {

    private SpeechSynthesisModel speechSynthesisModel;

    public AudioModelController(SpeechSynthesisModel speechSynthesisModel) {
        this.speechSynthesisModel = speechSynthesisModel;
    }

    @RequestMapping("/model")
    public ResponseEntity<byte[]> model(String input) {
//        构建语音合成请求
        SpeechSynthesisPrompt prompt = new SpeechSynthesisPrompt(input);
//        调用模型生成语音
        SpeechSynthesisResponse call = speechSynthesisModel.call(prompt);
        ByteBuffer audio = call.getResult().getOutput().getAudio();
//        将ByteBuffer转换为字节数组
        byte[] bytes = new byte[audio.remaining()];
        audio.get(bytes);
//        返回流音频
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header("Content-Disposition", "attachment; filename=output.mp3")
                .body(bytes);
    }

}
